import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'

const USER_COOKIE_KEY = 'user'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    userId: '',
    permissions: [],
    currentUser: Cookies.get(USER_COOKIE_KEY)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          Cookies.set(USER_COOKIE_KEY, JSON.stringify(response), {expires: 30, path: '/'})

          const tokenStr = username+response.userId
          setToken(tokenStr)
          commit('SET_TOKEN', tokenStr)
          commit('SET_NAME', username)
          commit('SET_USERID', response.userId)
          commit('SET_AVATAR', response.icon ? 'http://xiaochaguan.yihuyixi.com/ps/download/'+response.icon : '')
          getInfo(response.userId).then(res => {
            const data = res
            var permissions = data && data.info || [];
            commit('SET_PERMISSIONS', permissions)
            resolve(res)
          }).catch(err => {
            reject(err)
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_ROLES', ['TEST'])
        // commit('SET_NAME', 'admin')
        // resolve({})
        if (state.currentUser) {
          let currentUser = JSON.parse(state.currentUser)
          if (currentUser.icon && currentUser.icon.indexOf('http') == -1) {
            currentUser.icon = '/ps/download/' + currentUser.icon;
          }
          commit('SET_NAME', currentUser.username)
          commit('SET_USERID', currentUser.userId)
          commit('SET_AVATAR', currentUser.icon ? currentUser.icon : 'http://xiaochaguan.yihuyixi.com/ps/download/5d6f86d0e4b074d3d7411da5')
          getInfo(currentUser.userId).then(response => {
            const data = response
            var permissions = data && data.info || [];
            commit('SET_PERMISSIONS', permissions)
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        } else {
          reject();
        }
      })
    },

    // 登出
    LogOut({ commit, state }) {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      return new Promise((resolve, reject) => {
        var userId = -1;
        if (state.currentUser) {
          let user = JSON.parse(state.currentUser);
          userId = user.userId || -1;
        }
        logout(userId).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          Cookies.remove(USER_COOKIE_KEY)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        Cookies.remove(USER_COOKIE_KEY)
        resolve()
      })
    }
  }
}

export default user
